#include "FKDisplayReferent.h"

#include "FKDrawModel.h"
#include "FKWorldReferent.h"

#include "../FKTools/FKLogger.h"

FKWorldReferent* FKDisplayReferent::_world=0;

FKDisplayReferent::FKDisplayReferent(QString modelName, qint32 sourceID, QObject* parent):QObject(parent),
        /*_pos(0,0,0),_orientation(),*/_scale(1,1,1),_color(),_visible(false),_sourceID(sourceID),_calculated(false){
    FK_CBEGIN
    _model=0;
    setModel(modelName);
    FK_CEND
}

FKDisplayReferent::~FKDisplayReferent(){
    FK_DBEGIN
    if(_model)_model->removeReferent(this);
    FK_DEND
}

void FKDisplayReferent::setModel(const QString &modelName){
    if(_world){
        _model=_world->getModel(modelName);
        if(_model)_model->addReferent(this); else{FK_MLOGV("World referent has no such model",modelName)}
    }else{
        FK_MLOG("World referent is null")
        _model=0;
    }
}

const QString FKDisplayReferent::modelName() const {
    if(_model)return _model->modelName();
    else return QString();
}

QMatrix4x4 FKDisplayReferent::getMatrix(){
    if(!_calculated)calculateMatrix();
    return _mMat;
}

void FKDisplayReferent::calculateMatrix(){
    _mMat.setToIdentity();
    _mMat.translate(_pos);
    _mMat.scale(_scale);
    _mMat.rotate(_rotation);
    _calculated=true;
}

void FKDisplayReferent::setPos(QVector3D pos){
    if(_pos!=pos){
        _calculated=false;
        _pos=pos;
    }
}

void FKDisplayReferent::move(QVector3D pos){
    _calculated=false;
    _pos+=pos;
}

void FKDisplayReferent::rotate(const QQuaternion& q){
    _calculated=false;
    _rotation=q*_rotation;
}

void FKDisplayReferent::setRotation(const QQuaternion& q){
    _calculated=false;
    _rotation=q;
}

void FKDisplayReferent::setScale(QVector3D m){
    _calculated=false;
    _scale=m;
}
